
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QFileInfo>
#include <QMessageBox>
#include <QMimeData>
#include <QProcess>
#include <QStandardPaths>
#include <QTextStream>
#include <QTextCodec>
#include <config.h>
#include <QDebug>
#include <QFileIconProvider>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->do_fast_flashall->hide();
    ui->do_fast_update_zip->hide();
    ui->do_fast_flash_bootloader->hide();
    ui->do_fast_flash_radio->hide();

    ui->transfer_remount_system->hide();

    ui->status->setText("就绪.");
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));
}
MainWindow::~MainWindow()
{

}

void MainWindow::connectProcess(QProcess *process)
{
    process->setReadChannelMode(QProcess::MergedChannels);
    connect(process, &QProcess::readyRead,[=](){
        QString out = process->readAll().trimmed();
        if (!out.isEmpty())
            ui->textEdit->append(out);
    });
    connect(process, static_cast<void(QProcess::*)(int)>(&QProcess::finished),[=](int exitCode){
        QString out = process->readAll().trimmed();
        if (!out.isEmpty())
            ui->textEdit->append(out);
        ui->status->setText("完成.");
        process->deleteLater();
    });
    connect(process, &QProcess::errorOccurred, this, [=](){
        int err_code  = process->exitCode();
        QString err = process->errorString();
        ui->status->setText("失败.");
        ui->textEdit->append(err);
        process->deleteLater();
    });
}

QProcess *MainWindow::createConnectProcess()
{
    QProcess *process = new QProcess;
    connectProcess(process);
    return process;
}

void MainWindow::runConnectProcessCommand(const QString &command)
{
    QString text = QString("正在执行: '%1'.").arg(command);
    // QFontMetrics fontWidth(ui->status->font());     //得到每个字符的宽度
    // QString elideText = fontWidth.elidedText(text, Qt::ElideRight, ui->lineEdit->width());//最大宽度150像素
    // ui->status->setText(elideText);
    
    ui->status->setText(text);
    QProcess *process = createConnectProcess();
    process->start(command);
}

void MainWindow::runEnableConnectProcessCommand(const QString &command, QWidget *widget)
{
    QString text = QString("正在执行: '%1'.").arg(command);
    // QFontMetrics fontWidth(ui->status->font());     //得到每个字符的宽度
    // QString elideText = fontWidth.elidedText(text, Qt::ElideRight, ui->lineEdit->width());//最大宽度150像素
    // ui->status->setText(elideText);
    
    ui->status->setText(text);
    QProcess *process = createConnectProcess();
    connect(process, static_cast<void(QProcess::*)(int)>(&QProcess::finished), this, [=](int exitCode){
        widget->setEnabled(true);
    });
    connect(process, &QProcess::started, this, [=](){
        widget->setEnabled(false);
    });
    connect(process, &QProcess::errorOccurred, this, [=](){
        widget->setEnabled(true);
    });
    process->start(command);
}

void MainWindow::runWaitConnectProcessCommand(const QString &command)
{
    ui->status->setText(QString("正在执行(请等待): '%1'.").arg(command));
    repaint();
    QProcess *process = createConnectProcess();
    process->start(command);
    process->waitForFinished();
}

bool MainWindow::isChoosedImgDir()
{
    QFileInfo fi(ui->lineEdit->text());
    if (fi.exists() && fi.isDir()) {
        QDir dir(ui->lineEdit->text());
        QFileInfoList list = dir.entryInfoList();
        if (fileInfoListHasName(list, "system.img")) {
            ui->status->setText("选择AOSP镜像输出目录：已选中.");

            // 如果手动更新内容为空，将触发选中
            if(ui->lineEdit4ImagesDir->text().isEmpty()) {
                ui->lineEdit4ImagesDir->setText(dir.path());
            }
            return true;
        }
    }
    ui->status->setText("选择AOSP镜像输出目录：目录中必须包含(system.img,boot.img,vendor.img)等文件.");
    return false;
}

bool MainWindow::isChoosedBootImg()
{
    QFileInfo fi(ui->lineEditBoot->text());
    if (fi.exists() && fi.isFile() && fi.suffix().compare("img")==0) {
        return true;
    }
    return false;
}

bool MainWindow::isChoosedUpdateZip()
{
    QFileInfo fi(ui->lineEditUpdateZip->text());
    if (fi.exists() && fi.isFile() && fi.suffix().compare("zip")==0) {
        ui->status->setText("更新文件: 已选中 zip 文件.");
        return true;
    }
    ui->status->setText("更新文件: 未选中 zip 文件.");
    return false;
}

bool MainWindow::isChoosedBootLoaderImg()
{
    QFileInfo fi(ui->lineEditBootLoader->text());
    if (fi.exists() && fi.isFile() && fi.suffix().compare("img")==0) {
        ui->status->setText("bootloader镜像文件: 已选中 bootloader 镜像文件.");
        return true;
    }
    ui->status->setText("Bootloader镜像文件: 未选中 Bootloader 镜像文件.");
    return false;
}

bool MainWindow::isChoosedRadioImg()
{
    QFileInfo fi(ui->lineEditRadioImg->text());
    if (fi.exists() && fi.isFile() && fi.suffix().compare("img")==0) {
        ui->status->setText("radio镜像文件: 已选中 radio 镜像文件.");
        return true;
    }
    ui->status->setText("radio镜像文件: 未选中 radio 镜像文件.");
    return false;
}

bool MainWindow::isChoosedManualUpdateImgDir()
{
    QFileInfo fi(ui->lineEdit4ImagesDir->text());
    if (fi.exists() && fi.isDir()) {
        QDir dir(ui->lineEdit4ImagesDir->text());
        QFileInfoList list = dir.entryInfoList();
        if (fileInfoListHasName(list, "system.img")) {
            ui->status->setText("选择AOSP镜像输出目录：已选中.");

//            // 如果手动更新内容为空，将触发选中
//            if(ui->lineEdit4ImagesDir->text().isEmpty()) {
//                ui->lineEdit4ImagesDir->setText(dir.path());
//            }
            return true;
        }
    }
    ui->status->setText("选择AOSP镜像输出目录：目录中必须包含(system.img,boot.img,vendor.img)等文件.");
    return false;
}

bool MainWindow::fileInfoListHasName(const QFileInfoList &list, QString filename)
{
    foreach (auto item , list) {
        QTextStream(stdout) << "item:" << item.fileName() << "\n";
        if (item.fileName().compare(filename) == 0) {
            return true;
        }
    }
    return false;
}

QMessageBox* MainWindow::createEraseWarringMessage(const QString &partition)
{
    QMessageBox *msg = new QMessageBox;
    msg->setIcon(QMessageBox::Warning);
    msg->setText("请注意:");
    msg->setInformativeText(QString("确定是否擦除 %1 分区?").arg(partition));
    msg->setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msg->setDefaultButton(QMessageBox::Cancel);
    connect(msg, &QMessageBox::rejected, this, [=](){
        ui->status->setText(QString("已取消擦除 %1 分区操作.").arg(partition));
    });
    return msg;
}

QMessageBox *MainWindow::createFlashWarringMessage(const QString &partition)
{
    QMessageBox *msg = new QMessageBox;
    msg->setIcon(QMessageBox::Warning);
    msg->setText("请注意:");
    msg->setInformativeText(QString("确定是否刷入 %1 分区?").arg(partition));
    msg->setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msg->setDefaultButton(QMessageBox::Cancel);
    connect(msg, &QMessageBox::rejected, this, [=](){
        ui->status->setText(QString("已取消刷入 %1 分区操作.").arg(partition));
    });
    return msg;
}

QMessageBox* MainWindow::createFlashSystemWarringMessage()
{
    QMessageBox *msg = new QMessageBox;
    msg->setIcon(QMessageBox::Warning);
    msg->setText("请注意:");
    msg->setInformativeText(QString("确定是否刷入系统?"));
    msg->setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msg->setDefaultButton(QMessageBox::Cancel);
    connect(msg, &QMessageBox::rejected, this, [=](){
        ui->status->setText(QString("已取消刷入系统操作."));
    });
    return msg;
}

QMessageBox *MainWindow::createUpdateWarringMessage()
{
    QMessageBox *msg = new QMessageBox;
    msg->setIcon(QMessageBox::Warning);
    msg->setText("请注意:");
    msg->setInformativeText(QString("确定是否进行更新?"));
    msg->setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msg->setDefaultButton(QMessageBox::Cancel);
    connect(msg, &QMessageBox::rejected, this, [=](){
        ui->status->setText(QString("已取消更新操作."));
    });
    return msg;
}

QMessageBox* MainWindow::createTransferFilesWarringMessage(const QStringList &fileNames)
{
    QMessageBox *msg = new QMessageBox;
    msg->setIcon(QMessageBox::Warning);
    msg->setText("确定是否传送这些文件?");
    msg->setInformativeText(fileNames.join("\n"));
    msg->setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
    msg->setDefaultButton(QMessageBox::Cancel);
    connect(msg, &QMessageBox::rejected, this, [=](){
        ui->status->setText(QString("已取消传送文件操作."));
    });
    return msg;
}

void MainWindow::on_adb_devices_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb devices", ui->adb_devices);
}

void MainWindow::on_adb_reboot_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb reboot", ui->adb_reboot);
}

void MainWindow::on_adb_reboot_bootloader_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb reboot bootloader", ui->adb_reboot_bootloader);
}

void MainWindow::on_adb_root_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb root", ui->adb_root);
}

void MainWindow::on_adb_shell_bootctl_current_slot_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb shell bootctl get-current-slot", ui->adb_shell_bootctl_current_slot);
}

void MainWindow::on_adb_bootctl_next_a_clicked()
{
    ui->textEdit->append("在下次引导时，加载并执行SLOT A.");
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb shell bootctl set-active-boot-slot 0", ui->adb_bootctl_next_a);
}

void MainWindow::on_adb_bootctl_next_b_clicked()
{
    ui->textEdit->append("在下次引导时，加载并执行SLOT B.");
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb shell bootctl set-active-boot-slot 1", ui->adb_bootctl_next_b);
}

void MainWindow::on_adb_kill_server_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"adb kill-server", ui->adb_kill_server);
}

void MainWindow::on_fast_reboot_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot reboot", ui->fast_reboot);
}

void MainWindow::on_fast_reboot_bootloader_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot reboot bootloader", ui->fast_reboot_bootloader);
}

void MainWindow::on_fast_set_a_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot set_active a", ui->fast_set_a);
}

void MainWindow::on_fast_set_b_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot set_active b",ui->fast_set_b);
}

void MainWindow::on_fast_getvar_all_clicked()
{
    runWaitConnectProcessCommand("echo '---------getvar all-----------'");
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar all", ui->fast_getvar_all);
}

void MainWindow::on_fast_getvar_some_clicked()
{
    runWaitConnectProcessCommand("echo '---------getvar some-----------'");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar has-slot:boot");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar current-slot");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-successful:a");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-unbootable:a");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-retry-count:a");
    runConnectProcessCommand("echo");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-unbootable:b");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-successful:b");
    runConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-retry-count:b");
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar slot-count", ui->fast_getvar_some);
}


void MainWindow::on_fast_getvar_current_slot_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot getvar current-slot", ui->fast_getvar_current_slot);
}


void MainWindow::on_fast_devices_clicked()
{
    runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot devices", ui->fast_devices);
}

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    if (isChoosedImgDir()) {
        ui->do_fast_flashall->show();
        ui->chooseDir->hide();
    } else {
        ui->do_fast_flashall->hide();
        ui->chooseDir->show();
    }
}

void MainWindow::on_chooseDir_clicked()
{
    QString dialogPath = QStandardPaths::displayName(QStandardPaths::HomeLocation);
    if (QDir(ui->lineEdit->text()).exists()) {
        dialogPath = ui->lineEdit->text();
    }
    QString path = QFileDialog::getExistingDirectory(this, "选择AOSP镜像输出目录", dialogPath, QFileDialog::ReadOnly);
    if (path.isEmpty()) return;
    ui->lineEdit->setText(path);
}

void MainWindow::on_do_fast_flashall_clicked()
{
    QString path = ui->lineEdit->text();
    if (path.isEmpty()) {

    }
    QFileInfo fi(path);
    if (!fi.exists()) return;

    QMessageBox *msg = createFlashSystemWarringMessage();
    int ret = msg->exec();
    if (ret == QMessageBox::Yes) {
        // export ANDROID_PRODUCT_OUT=out/target/product/walleye/
        setenv("ANDROID_PRODUCT_OUT", path.toLocal8Bit().constData(), 1);

        QStringList flashargs;
        if (ui->check_flash_args_erase_userdata->isChecked())
            flashargs << "-w";
        if (ui->check_flash_args_disable_verity->isChecked())
            flashargs << "--disable-verity";
        if (ui->check_flash_args_skip_secondary->isChecked())
            flashargs << "--skip-secondary";
        if (ui->check_flash_args_skip_reboot->isChecked())
            flashargs << "--skip-reboot";

        QTextStream out(stdout);
        out << QString(PLATFORM_TOOLS"fastboot flashall %1").arg(flashargs.join(" ")) << "\n";
        runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot flashall %1").arg(flashargs.join(" ")), ui->do_fast_flashall);
    }
    msg->deleteLater();
}


void MainWindow::on_do_fast_erase_userdata_clicked()
{
    QMessageBox *msg = createEraseWarringMessage("userdata");
    int ret = msg->exec();
    if (ret == QMessageBox::Yes) {
        runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot erase userdata", ui->do_fast_erase_userdata);
    }
    msg->deleteLater();
}

void MainWindow::on_do_fast_erase_boot_clicked()
{
    QMessageBox *msg = createEraseWarringMessage("boot");
    int ret = msg->exec();
    if (ret == QMessageBox::Yes) {
        runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot erase boot", ui->do_fast_erase_boot);
    }
    msg->deleteLater();
}

void MainWindow::on_do_fast_erase_system_clicked()
{
    QMessageBox *msg = createEraseWarringMessage("system");
    int ret = msg->exec();
    if (ret == QMessageBox::Yes) {
        runEnableConnectProcessCommand(PLATFORM_TOOLS"fastboot erase system",ui->do_fast_erase_system);
    }
    msg->deleteLater();
}

void MainWindow::on_lineEditBoot_textChanged(const QString &arg1)
{
    bool enableState = false;
    if (isChoosedBootImg()) {
        enableState = true;
    } else {
        ui->status->setText("Boot镜像文件: 未选中Boot镜像文件.");
    }
    ui->do_fast_boot->setEnabled(enableState);
    ui->do_fast_flash_recovery->setEnabled(enableState);
    ui->do_fast_flash_boot->setEnabled(enableState);
}

void MainWindow::on_chooseBootFile_clicked()
{
    QString dialogPath = QStandardPaths::displayName(QStandardPaths::HomeLocation);
    if (QDir(ui->lineEditBoot->text()).exists()) {
        dialogPath = ui->lineEdit->text();
    }
    QString path = QFileDialog::getOpenFileName(this, "选择Boot镜像文件", dialogPath, "BootImg (*.img)");
    if (path.isEmpty()) return;
    ui->lineEditBoot->setText(path);
}

void MainWindow::on_do_fast_flash_recovery_clicked()
{
    if (isChoosedBootImg()) {
        runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot flash recovery %1").arg(ui->lineEditBoot->text()), ui->do_fast_flash_recovery);
    }
}

void MainWindow::on_do_fast_flash_boot_clicked()
{
    if (isChoosedBootImg()) {
        QMessageBox *msg = createFlashWarringMessage("boot");
        int ret = msg->exec();
        if (ret == QMessageBox::Yes) {
            runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot flash boot %1").arg(ui->lineEditBoot->text()), ui->do_fast_flash_boot);
        }
        msg->deleteLater();
    }
}

void MainWindow::on_do_fast_boot_clicked()
{
    if (isChoosedBootImg()) {
        runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot boot %1").arg(ui->lineEditBoot->text()), ui->do_fast_boot);
    }
}

void MainWindow::on_textEdit_textChanged()
{
    if (ui->checkBox->checkState() == Qt::CheckState::Checked) {
        ui->textEdit->moveCursor(QTextCursor::End);
    }
}


void MainWindow::on_lineEditUpdateZip_textChanged(const QString &arg1)
{

    if (isChoosedUpdateZip()) {
        ui->do_fast_update_zip->show();
        ui->chooseUpdateZip->hide();
    } else {
        ui->do_fast_update_zip->hide();
        ui->chooseUpdateZip->show();
    }
}

void MainWindow::on_chooseUpdateZip_clicked()
{
    QString dialogPath = QStandardPaths::displayName(QStandardPaths::HomeLocation);
    if (QDir(ui->lineEditUpdateZip->text()).exists()) {
        dialogPath = ui->lineEditUpdateZip->text();
    }
    QString path = QFileDialog::getOpenFileName(this, "选择 zip 文件", dialogPath, "Zip (*.zip)");
    if (path.isEmpty()) return;
    ui->lineEditUpdateZip->setText(path);
}

void MainWindow::on_do_fast_update_zip_clicked()
{
    if (isChoosedUpdateZip()) {
        QMessageBox *msg = createUpdateWarringMessage();
        int ret = msg->exec();
        if (ret == QMessageBox::Yes) {
            if (ui->check_flash_args_erase_userdata_with_update->isChecked()) {
                runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot -w update %1 ").arg(ui->lineEditUpdateZip->text()), ui->do_fast_update_zip);
            } else {
                runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot update %1").arg(ui->lineEditUpdateZip->text()), ui->do_fast_update_zip);
            }
        }
        msg->deleteLater();
    }
}

void MainWindow::on_lineEditBootLoader_textChanged(const QString &arg1)
{
    if (isChoosedBootLoaderImg()) {
        ui->do_fast_flash_bootloader->show();
        ui->chooseBootLoader->hide();
    } else {
        ui->do_fast_flash_bootloader->hide();
        ui->chooseBootLoader->show();
    }
}

void MainWindow::on_chooseBootLoader_clicked()
{
    QString dialogPath = QStandardPaths::displayName(QStandardPaths::HomeLocation);
    if (QDir(ui->lineEditBootLoader->text()).exists()) {
        dialogPath = ui->lineEditBootLoader->text();
    }
    QString path = QFileDialog::getOpenFileName(this, "选择Bootloader镜像文件", dialogPath, "BootloaderImg (*.img)");
    if (path.isEmpty()) return;
    ui->lineEditBootLoader->setText(path);
}

void MainWindow::on_do_fast_flash_bootloader_clicked()
{
    if (isChoosedBootLoaderImg()) {
        QMessageBox *msg = createFlashWarringMessage("bootloader");
        int ret = msg->exec();
        if (ret == QMessageBox::Yes) {
            runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot flash bootloader %1").arg(ui->lineEditBootLoader->text()), ui->do_fast_flash_bootloader);
        }
        msg->deleteLater();
    }
}

void MainWindow::on_lineEditRadioImg_textChanged(const QString &arg1)
{
    if (isChoosedRadioImg()) {
        ui->do_fast_flash_radio->show();
        ui->chooseRadioImg->hide();
    } else {
        ui->do_fast_flash_radio->hide();
        ui->chooseRadioImg->show();
    }
}

void MainWindow::on_chooseRadioImg_clicked()
{
    QString dialogPath = QStandardPaths::displayName(QStandardPaths::HomeLocation);
    if (QDir(ui->lineEditRadioImg->text()).exists()) {
        dialogPath = ui->lineEditRadioImg->text();
    }
    QString path = QFileDialog::getOpenFileName(this, "选择 radio 镜像文件", dialogPath, "radio (*.img)");
    if (path.isEmpty()) return;
    ui->lineEditRadioImg->setText(path);
}

void MainWindow::on_do_fast_flash_radio_clicked()
{
    if (isChoosedRadioImg()) {
        QMessageBox *msg = createFlashWarringMessage("radio");
        int ret = msg->exec();
        if (ret == QMessageBox::Yes) {
            runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot flash radio %1").arg(ui->lineEditRadioImg->text()), ui->do_fast_flash_radio);
        }
        msg->deleteLater();
    }
}


void MainWindow::on_lineEdit4ImagesDir_textChanged(const QString &arg1)
{
    if (isChoosedManualUpdateImgDir()) {
        ui->manual_updata_listwidget->clear();
        QDir dir(ui->lineEdit4ImagesDir->text());
        foreach(auto entry , dir.entryInfoList()) {
            QRegExp reg("[a-z]*.img");
            int pos = reg.indexIn(entry.fileName(), 0);

            if (pos == 0 && entry.fileName().endsWith("img") && entry.fileName().compare(reg.cap(0)) == 0) {

                QListWidgetItem *item = new QListWidgetItem;
                item->setData(Qt::UserRole, entry.absoluteFilePath());
                item->setText(entry.fileName());
                QFileIconProvider profider;
                QIcon icon =  profider.icon(entry);
                item->setIcon(icon);
                ui->manual_updata_listwidget->addItem(item);
            }
        }
//        ui->manual_update_fast_flash->setEnabled(true);
//        ui->manual_update_fast_erase->setEnabled(true);
    } else {
        ui->manual_updata_listwidget->clear();
        ui->manual_update_fast_flash->setEnabled(false);
        ui->manual_update_fast_erase->setEnabled(false);
    }
}

void MainWindow::on_manual_update_chooseDir_clicked()
{
    on_chooseDir_clicked();
}

void MainWindow::on_manual_updata_listwidget_itemSelectionChanged()
{
    QListWidgetItem *item = ui->manual_updata_listwidget->currentItem();
    if (item != nullptr) {
        ui->manual_update_fast_flash->setEnabled(true);
        ui->manual_update_fast_erase->setEnabled(true);
        on_manual_updata_listwidget_currentTextChanged(item->text());
    }
}

void MainWindow::on_manual_update_fast_flash_clicked()
{
    QListWidgetItem *item = ui->manual_updata_listwidget->currentItem();
    QString partition = item->text().split(".")[0];
    QString imagePath = item->data(Qt::UserRole).toString();
    qDebug() << "imagePath:" << imagePath;
    if (QFileInfo::exists(imagePath))
        runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot flash %1 %2")
                                            .arg(partition)
                                            .arg(imagePath),
                                       ui->manual_update_fast_flash);
}

void MainWindow::on_manual_update_fast_erase_clicked()
{
    QListWidgetItem *item = ui->manual_updata_listwidget->currentItem();
    QString partition = item->text().split(".")[0];
    QMessageBox *msg = createEraseWarringMessage(partition);
    int ret = msg->exec();
    if (ret == QMessageBox::Yes) {
        runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot erase %1").arg(partition), ui->manual_update_fast_erase);
    }
    msg->deleteLater();
}

void MainWindow::on_manual_updata_listwidget_currentTextChanged(const QString &currentText)
{
    if (currentText.contains("bootloader")) {
        ui->manual_update_fast_erase->setEnabled(false);
    }
    ui->status->setText(QString("当前选中: %1").arg(currentText));
}

void MainWindow::dropTrasferFiles(QDropEvent *event)
{
    QString target = "";
    QStringList commands;

    if (ui->transfer_data->isChecked()) {
        target = "/data";
    }
    if (ui->transfer_data_local_tmp->isChecked()) {
        target = "/data/local/tmp";
    }
    if (ui->transfer_system_bin->isChecked()) {
        target = "/system/bin";
        if (ui->transfer_remount_system->isChecked()) {
            commands << QString(PLATFORM_TOOLS"adb root");
            commands << QString(PLATFORM_TOOLS"adb remount");
        }
    }
    if (ui->transfer_sdcard->isChecked()) {
        target = "/sdcard";
    }

    QStringList fileNames;
    const QMimeData *meta = event->mimeData();
    if (meta->hasUrls()) {
        foreach(auto url, meta->urls()) {
            QString path = url.toLocalFile();

            QFileInfo fi(path);
            if (fi.exists() && fi.isFile()) {
                QString command = QString(PLATFORM_TOOLS"adb push %1 %2").arg(fi.absoluteFilePath()).arg(target);
                commands << command;
                fileNames << fi.fileName();
                if (ui->transfer_data->isChecked() || ui->transfer_system_bin->isChecked()) {
                    if (ui->transfer_executable->isChecked()) {
                        commands << QString(PLATFORM_TOOLS"adb shell chmod +x %1/%2").arg(target).arg(fi.fileName());
                    }
                }
            }
        }
    }

    QMessageBox *msg = createTransferFilesWarringMessage(fileNames);
    int ret = msg->exec();
    if (ret == QMessageBox::Yes) {
        foreach(auto command, commands) {
            ui->textEdit->append(command);
            runEnableConnectProcessCommand(command, ui->transfer_drop_label);
        }
    }
    msg->deleteLater();
    event->ignore();
}

void MainWindow::dropUpdateFolder(QDropEvent *event)
{
    const QMimeData *meta = event->mimeData();
    if (meta->hasUrls()) {
        foreach(auto url, meta->urls()) {
            QString path = url.toLocalFile();

            QFileInfo fi(path);
            if (fi.exists() && fi.isDir()) {
//                QString command = QString(PLATFORM_TOOLS"adb push %1 %2").arg(fi.absoluteFilePath()).arg(target);
                foreach(auto entry , QDir(path).entryInfoList()) {
                    if (entry.fileName().startsWith("bootloader") && entry.fileName().endsWith("img")) {
                        ui->lineEditBootLoader->setText(entry.absoluteFilePath());
                    }

                    if (entry.fileName().startsWith("radio") && entry.fileName().endsWith("img")) {
                        ui->lineEditRadioImg->setText(entry.absoluteFilePath());
                    }

                    if (entry.fileName().endsWith("zip")) {
                        ui->lineEditUpdateZip->setText(entry.absoluteFilePath());
                    }
                }
            }

            if (fi.exists() && fi.isFile()) {
//                QString command = QString(PLATFORM_TOOLS"adb push %1 %2").arg(fi.absoluteFilePath()).arg(target);
                if (fi.fileName().startsWith("bootloader") && fi.fileName().endsWith("img")) {
                    ui->lineEditBootLoader->setText(fi.absoluteFilePath());
                }

                if (fi.fileName().startsWith("radio") && fi.fileName().endsWith("img")) {
                    ui->lineEditRadioImg->setText(fi.absoluteFilePath());
                }

                if (fi.fileName().endsWith("zip")) {
                    ui->lineEditUpdateZip->setText(fi.absoluteFilePath());
                }
            }
        }
    }
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if (ui->tabWidget->currentIndex() != 0)
        event->acceptProposedAction();
}

void MainWindow::dragMoveEvent(QDragMoveEvent *event)
{
    ui->status->setText(QString("x: %1, y: %2").arg(event->pos().x()).arg(event->pos().y()));
}

void MainWindow::dropEvent(QDropEvent *event)
{
    if (ui->tabWidget->currentIndex() == 2)
        dropTrasferFiles(event);
    if (ui->tabWidget->currentIndex() == 1)
        dropUpdateFolder(event);
}


void MainWindow::on_transfer_data_clicked()
{
    if (ui->transfer_data->isChecked()) {
        ui->transfer_executable->show();
        ui->transfer_remount_system->hide();
    }
}

void MainWindow::on_transfer_system_bin_clicked()
{
    if (ui->transfer_system_bin->isChecked()) {
        ui->transfer_executable->show();
        ui->transfer_remount_system->show();
    }
}

void MainWindow::on_transfer_sdcard_clicked()
{
    if (ui->transfer_sdcard->isChecked()) {
        ui->transfer_executable->hide();
        ui->transfer_remount_system->hide();
    }
}

void MainWindow::on_other_fastboot_reboot_fastbootd_clicked()
{
    runEnableConnectProcessCommand(QString(PLATFORM_TOOLS"fastboot reboot fastboot"), ui->other_fastboot_reboot_fastbootd);
}
